package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.Utilities;

import beans.Chapterbean;
import beans.KnowledgePointbean;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import dao.Knowledgepoint;

public class KnowledgeManageServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {

	response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.println("<HTML>");
	out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
	out.println("  <BODY>");
	out.print("    This is ");
	out.print(this.getClass());
	out.println(", using the GET method");
	out.println("  </BODY>");
	out.println("</HTML>");
	out.flush();
	out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	if (request.getQueryString() != null) {
	    String actionString = request.getParameter("action").trim();
	    if ("add".equals(actionString)) {
		StringBuffer pathString = new StringBuffer("/image/examples/");
		SmartUpload su = new SmartUpload();
		su.initialize(this.getServletConfig(), request, response);
		su.setMaxFileSize(5000000);
		su.setAllowedFilesList("jpg,jpeg,png");
		try {
		    su.upload();
		} catch (SmartUploadException e) {
		    e.printStackTrace();
		}
		Request request2 = su.getRequest();
		String chapterId = request2.getParameter("chapterId");
		String knowledgeType = request2.getParameter("knowledgeType");
		String description = new String(request2
			.getParameter("description").trim().getBytes("gbk"),
			"utf-8");
		String example = new String(request2.getParameter("example")
			.trim().getBytes("gbk"), "utf-8");
		String title = new String(request2.getParameter("title")
			.trim().getBytes("gbk"), "utf-8");
		Files files = su.getFiles();
		File file = files.getFile(0);
		if (!file.isMissing()) {
		    int pos = file.getFileName().lastIndexOf(".");
		    pathString.append(Utilities.makeImageName()).append(
			    file.getFileName().substring(pos));

		    java.io.File imgFile = new java.io.File(request
			    .getSession().getServletContext()
			    .getRealPath(pathString.toString()));
		    while (imgFile.exists()) {
			pathString = new StringBuffer("/image/examples/");
			pathString.append(Utilities.makeImageName()).append(
				file.getFileName().substring(pos));
			imgFile = new java.io.File(request.getSession()
				.getServletContext()
				.getRealPath(pathString.toString()));
		    }

		    try {
			file.saveAs(pathString.toString(),
				SmartUpload.SAVE_VIRTUAL);
		    } catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		}
		Knowledgepoint knowledgepoint = new Knowledgepoint();
		knowledgepoint.setDescription(description);
		knowledgepoint.setKnowledgetype(knowledgeType);
		knowledgepoint.setPath(pathString.toString());
		knowledgepoint.setExample(example);
		knowledgepoint.setChapterid(chapterId);
		knowledgepoint.setTitle(title);
		KnowledgePointbean knowledgePointbean = new KnowledgePointbean();
		if (knowledgePointbean.addKnowledgePoint(knowledgepoint)) {
		    request.setAttribute("success", "true");
		} else {
		    request.setAttribute("success", "false");
		}
		request.getRequestDispatcher("../teacher/addKnowledgePoint.jsp")
			.forward(request, response);
	    }else if("getSourceKnowledges".equals(actionString)){
		String chapterid = request.getParameter("chapterid").trim();
		KnowledgePointbean knowledgePointbean = new KnowledgePointbean();
		response.getWriter().write(knowledgePointbean.getSourceKnowledges(chapterid));
		
	    }else if("getDesKnowledges".equals(actionString)){
		String chapterid = request.getParameter("chapterid").trim();
		String knowledgeid = request.getParameter("source").trim();
		KnowledgePointbean knowledgePointbean = new KnowledgePointbean();
		response.getWriter().write(knowledgePointbean.getDesKnowledges(chapterid, knowledgeid));
	    }
	}
    }
}
